import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    DATETIME_FORMAT,
} from '../constants';
import styles from './style.css';
import {Link} from 'react-router-dom';
import {injectIntl, formatMessage} from './intl';
import {hasPermissions, conventSorter} from './utils';
import {currency, claimSettlementBillStatus} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
export class TablePanel extends React.PureComponent {
    handleSubmit = id => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    
    handleReSettle = id => {
        this.setState({
            loading: true
        });
        this.props.onClickReSettlement(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    render() {
        const {permissions, isDealerUser, total, pageIndex, pageSize,
            onPageIndexChange, onPageSizeChange, errorMessage, data, loading} = this.props;
        const columns = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '结算单号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>
            },
            {

                title: formatMessage({
                    id: 'tablePanel.column.brand',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brandCode',
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.technologyActivityName',
                    defaultMessage: '技术升级主题'
                }),
                dataIndex: 'technologyActivityName'
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.laborFee',
                    defaultMessage: '工时费'
                }),
                dataIndex: 'laborFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.materialFee',
                    defaultMessage: '材料费'
                }),
                dataIndex: 'materialFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.mgmtFee',
                    defaultMessage: '管理费'
                }),
                dataIndex: 'mgmtFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.assistantFee',
                    defaultMessage: '辅料费'
                }),
                dataIndex: 'assistantFee',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.totalFee',
                    defaultMessage: '费用合计'
                }),
                dataIndex: 'totalFee',
                sorter: true,
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                render: text => conventEnumValueToString(claimSettlementBillStatus, text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: ' 币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.creatorTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.approveTime',
                    defaultMessage: '结算日期'
                }),
                dataIndex: 'approveTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.submit,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleSubmit}>
                                    <a key="submit">
                                        {formatMessage({
                                            id: 'tablePanel.operation.submit',
                                            defaultMessage: '提交'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit))
                        },
                        {
                            id: PERMISSION.approve,
                            children: (
                                <Link key="approve" to={routes.approve.format(r.id)}>
                                    {formatMessage({
                                        id: 'tablePanel.operation.approve',
                                        defaultMessage: '财务审核'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve))
                        },
                        {
                            id: PERMISSION.reSettlement,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="reSettlement"
                                    title={formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleReSettle}>
                                    <a key="reSettlement">
                                        {formatMessage({
                                            id: 'tablePanel.operation.reSettlement',
                                            defaultMessage: '反结算'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(permissions, PERMISSION.reSettlement) &&
                                hasPermissions(r.options, PERMISSION.reSettlement))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {formatMessage({
                                            id: 'tablePanel.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        }
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const otherColums = [];
        if(isDealerUser) {
            otherColums.push(
                {
                    title: formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代号'
                    }),
                    sorter: true,
                    dataIndex: 'dealerCode'
                });
            columns.splice(1, 0, ...otherColums);
        }
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            onShowSizeChange: onPageSizeChange,
            onChange: onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={data}
                    rowKey="id"
                    pagination={pagination}
                    loading={loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickReSettlement: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {
    tableSearch,
    exportData,
    onClickAbandon,
    onClickSubmit,
    onClickReSettlement
} from './actions';
const EMPTY_ARRAY = [];
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: item.name,
            value: item.id
        }));
    }
);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    currentUserName: state.getIn(['page', 'domainData', 'initData', 'currentUserName']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state),
    brands: getBrandsData(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickExport: () => dispatch(exportData()),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickSubmit: id =>
        dispatch(onClickSubmit(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickReSettlement: id =>
        dispatch(onClickReSettlement(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
